<template>
  <a-row>
    <a-col class="leftCol" :span="6">
      <a-card class="card" :bordered="true">
        <div>
          <a-radio-group v-model="orgType">
            <a-radio style="radioStyle" value="org">单位</a-radio><br><br>
            <a-radio style="radioStyle" value="department">部门</a-radio><br><br>
            <!-- <a-radio style="radioStyle" :value="3">岗位</a-radio><br><br>
            <a-radio style="radioStyle" :value="4">人员</a-radio><br><br> -->
          </a-radio-group>
        </div>
      </a-card>
    </a-col>
    <a-col class="leftCol" :span="9">
      <a-card class="card" v-if="orgType==='org'" :bordered="true">
        <div>
          <a-table
            :columns="columns"
            :rowKey="record => record.pid"
            :customRow="tableRowClick"
            :dataSource="rolesData"
            :pagination="paginations"
            :rowClassName="setRowClassName"
            @change="onRoleTableChange"
          >
          </a-table>
        </div>
      </a-card>
      <!-- 部门权限 -->
      <a-card class="card" v-if="orgType==='department'" :bordered="true">
        <DepartTreeSelect
          @selectedDeparts="selectedDeparts"
        >
        </DepartTreeSelect>
      </a-card>
      <!-- 岗位权限 -->
      <!-- <a-card class="card" v-if="orgType===3" :bordered="true">
      </a-card> -->
      <!-- 人员权限 -->
      <!-- <a-card class="card" v-if="orgType===4" :bordered="true">
      </a-card> -->
    </a-col>
    <a-col :span="9">
      <a-card class="cardSelect" :bordered="true">
        <div class="selectAppId">
          选择应用:
          <a-select
            showSearch
            placeholder="选择应用"
            optionFilterProp="children"
            style="width: 200px"
            :filterOption="filterOption"
            v-model="huiwAppId"
            @change="appIdChange"
          >
            <a-select-option v-for="item in huiwAppIds" :value="item.appId" :key="item.appId">
              {{ item.appInfo }}
            </a-select-option>
          </a-select>
          <a-button style="margin-left: 5px" type="primary" shape="round" size="small" @click="getRoleManagerMenu" >查询</a-button>
        </div>
      </a-card>
      <a-card class="card" :loading="cardloading" :bordered="true">
        <a-row>
          <a-col :span="24">
            <a-radio-group v-model="authOpt" @change="authChange" defaultValue="1" buttonStyle="solid">
              <a-radio-button value="1">使用权限</a-radio-button>
              <a-radio-button value="__1">授权权限</a-radio-button>
            </a-radio-group>
            <a-button style="margin-left: 50px;" type="primary" @click="handleRoleMenuSave()">保存</a-button>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="24" style="border: 1px;">
            <a-spin size="large" :spinning="treeloading">
              <div class="tree-operations">
                <a-directory-tree
                  checkable
                  defaultExpandAll
                  :checkStrictly="checkStrictly"
                  :halfChecked="halfCheckedMenuKeys"
                  :checkedKeys="checkedMenuKeys"
                  @check="this.onChecked"
                  :treeData="treeData">
                </a-directory-tree>
              </div>
            </a-spin>
          </a-col>
        </a-row>
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import DepartTreeSelect from '@/views/sys/modules/DepartTreeSelect'
import { getMenuByParentMenu, getRolesList, getRolseCount, getMenuByrole, delMenuByrole, addMenuByrole } from './roleapi'
import zhCN from 'ant-design-vue/lib/locale-provider/zh_CN'
import storage from 'store'

export default {
  name: 'RoleManager',
  components: {
    DepartTreeSelect
  },
  data () {
    return {
      // 中文
      locale: zhCN,
      // 表头
      columns: [
        // {
        //   title: '#',
        //   dataIndex: 'no'
        // },
        {
          align: 'left',
          title: '名称',
          dataIndex: 'roleName',
          scopedSlots: { customRender: 'roleNameSlot' }
        }
      ],
      paginations: {
        showSizeChanger: true,
        showQuickJumper: true,
        defaultCurrent: 1,
        current: 1,
        total: 0,
        pageSize: 10
      },
      orgType: 'org',
      rolePid: '',
      rolesData: [{ roleName: storage.get('orgName'), pid: storage.get('org') }],
      selectedRowKeys: [], // 角色表选中
      clickedRowKey: '', // 角色选中角色Pid
      alertVisable: false,
      authOpt: '1',
      checkStrictly: true, // 树节点初始父子节点不关联，加载完成角色数据后，更改位关联
      selectedMenuKeys: [], // 角色权限树选中节点 包括半选节点
      checkedMenuKeys: [], // 菜单树显示选中节点
      halfCheckedMenuKeys: [], // 半选状态
      allHalfCheckedKeys: [], // 所有有子节点的key
      roleMenus: [], // 角色初始权限值
      roleAddMenus: [], // 角色增加权限值集
      roleDelMenus: [], // 角色删除权限值集
      huiwAppId: 'huiwcore',
      huiwAppIds: [
        { appId: 'huiwcore', appInfo: '平台应用' }
      ],
      cardloading: true,
      treeloading: false,
      treeData: [] // 菜单树
    }
  },
  created () {
    // this.form = this.$form.createForm(this)
    // this.getRolesData()
    this.appIdChange(this.huiwAppId)
  },
  mounted () {
  },
  methods: {
    selectedDeparts (val) {
      console.log(val)
      this.rolePid = val
      this.getRoleMenu(val)
    },
    // 查询角色权限
    getRoleMenu (rolePid) {
      if (rolePid) {
        this.clickedRowKey = rolePid
        this.checkStrictly = false
        this.selectedMenuKeys = []
        this.checkedMenuKeys = []
        this.roleAddMenus = []
        this.roleDelMenus = []
        this.roleMenus = []
        this.treeloading = true
        new Promise((resolve) => {
          resolve(getMenuByrole(this.huiwAppId, rolePid, { authOption: this.authOpt }))
        }).then((res) => {
          if (res && res.code === 'C1' && res.data) {
            const menus = res.data
            // console.log('allHalfCheckedKeys', this.allHalfCheckedKeys)
            for (var i = 0; i < menus.length; i++) {
              this.roleMenus.push(menus[i].pid)
              if (this.allHalfCheckedKeys.indexOf(menus[i].pid) < 0) {
                this.checkedMenuKeys.push(menus[i].pid)
              } else {
              }
            }
          }
          this.checkStrictly = false
          this.treeloading = false
        })
      }
    },
    // 总条数
    showTotal (total) {
      return `共 ${total} 条`
    },
    // 表格翻页等
    onRoleTableChange (params) {
      this.paginations.current = params.current
      this.paginations.pageSize = params.pageSize
      // this.getRolesData()
    },
    // 菜单树点击按钮
    onChecked (checkedMenuKeys, info) {
      const _this = this
      console.log('roleMenus', _this.roleMenus)
      _this.checkedMenuKeys = checkedMenuKeys
      _this.halfCheckedMenuKeys = info.halfCheckedKeys
      _this.selectedMenuKeys = [..._this.checkedMenuKeys, ..._this.halfCheckedMenuKeys]
      // 取交集
      const arrTmp = _this.selectedMenuKeys.filter(function (v) {
        return _this.roleMenus.indexOf(v) !== -1 // 利用filter方法来遍历是否有相同的元素
      })
      // 增加的菜单集
      _this.roleAddMenus = _this.selectedMenuKeys.concat(arrTmp).filter(function (v) {
        return _this.selectedMenuKeys.indexOf(v) === -1 || arrTmp.indexOf(v) === -1
      })
      // 删除的菜单集
      _this.roleDelMenus = _this.roleMenus.concat(arrTmp).filter(function (v) {
        return _this.roleMenus.indexOf(v) === -1 || arrTmp.indexOf(v) === -1
      })
      console.log('增加的菜单集', _this.roleAddMenus)
      console.log('删除的菜单集', _this.roleDelMenus)
    },
    // 表格记录勾选中
    onSelectChange (selectedRowKeys) {
      this.selectedRowKeys = selectedRowKeys
    },
    // 表格点击
    tableRowClick (record, index) {
      return {
        on: {
          click: () => {
            if (record && record.pid) {
              this.clickedRowKey = record.pid
              this.checkStrictly = false
              this.selectedMenuKeys = []
              this.checkedMenuKeys = []
              this.roleAddMenus = []
              this.roleDelMenus = []
              this.roleMenus = []
              this.treeloading = true
              new Promise((resolve) => {
                resolve(getMenuByrole(this.huiwAppId, record.pid, { authOption: this.authOpt }))
              }).then((res) => {
                if (res && res.code === 'C1' && res.data) {
                  const menus = res.data
                  // console.log('allHalfCheckedKeys', this.allHalfCheckedKeys)
                  for (var i = 0; i < menus.length; i++) {
                    this.roleMenus.push(menus[i].pid)
                    if (this.allHalfCheckedKeys.indexOf(menus[i].pid) < 0) {
                      this.checkedMenuKeys.push(menus[i].pid)
                    } else {
                    }
                  }
                }
                this.checkStrictly = false
                this.treeloading = false
              })
            }
          }
        }
      }
    },
    // 选择应用
    appIdChange (value) {
      console.log(value)
      if (value) {
        this.selectedKeys = [value]
        this.getRoleManagerMenu()
        this.addBtnShow = true
      }
    },
    // 权限类型变换
    authChange () {
      if (this.clickedRowKey) {
        this.checkStrictly = false
        this.selectedMenuKeys = []
        this.checkedMenuKeys = []
        this.roleAddMenus = []
        this.roleDelMenus = []
        new Promise((resolve) => {
          resolve(getMenuByrole(this.huiwAppId, this.clickedRowKey, { authOption: this.authOpt }))
        }).then((res) => {
          if (res && res.code === 'C1' && res.data) {
            const menus = res.data
            // console.log('allHalfCheckedKeys', this.allHalfCheckedKeys)
            for (var i = 0; i < menus.length; i++) {
              if (this.allHalfCheckedKeys.indexOf(menus[i].pid) < 0) {
                this.checkedMenuKeys.push(menus[i].pid)
              } else {
              }
            }
          }
          this.checkStrictly = false
        })
      }
    },
    // 查询角色列表
    getRolesData () {
      const param = {
        currentPage: this.paginations.current,
        pageSize: this.paginations.pageSize
      }
      getRolesList(param, {})
        .then(resd => {
          console.log('resd', resd)
          if (resd && resd.code === 'C1' && resd.data) {
            console.log(resd)
            this.rolesData = resd.data
          }
        })
      getRolseCount({}, {}).then(resd => {
        console.log(resd)
        if (resd && resd.code === 'C1' && resd.data) {
          this.paginations.total = resd.data
          this.paginations.showTotal = this.showTotal
          // if (this.paginations.current > (this.paginations.total / this.paginations.pageSize)) {
          //   console.log(this.paginations.total)
          //   this.paginations.current = this.paginations.total
          //   this.getRolesData()
          // }
        }
      })
    },
    // 角色菜单保存
    handleRoleMenuSave () {
      // let saveResult = true
      console.log(this.rolePid)
      const _this = this
      if (_this.roleDelMenus.length) {
        // 删除角色菜单权限
        const parameters = {
          appId: _this.huiwAppId,
          rolePid: _this.rolePid,
          roleType: 'role',
          resourceAuths: _this.roleDelMenus,
          authOpts: _this.authOpt
        }
        delMenuByrole(parameters, {}).then(res => {
          if (res && res.code === 'C1') {
            // saveResult = true
          } else {
            // saveResult = false
            _this.$message.error('授权出现错误')
          }
        })
      }
      if (_this.roleAddMenus.length > 0) {
        // 增加校色菜单权限
        const parameters = {
          sysSeq: 0,
          appId: _this.huiwAppId,
          rolePid: _this.clickedRowKey,
          roleType: 'role',
          resourceAuths: _this.roleAddMenus,
          authOpts: _this.authOpt
        }
        addMenuByrole(parameters, {}).then(res => {
          if (res && res.code === 'C1') {
            // saveResult = true
          } else {
            // saveResult = false
            _this.$message.error('授权出现错误')
          }
        })
      }
      // console.log(saveResult)
      // new Promise((resolve) => {
      //   resolve(() => {
      //     console.log(_this.roleDelMenus)
      //   })
      // }).then(() => {
      //   // if (!saveResult) {
      //   console.log(saveResult)
      //   // }
      // })
    },
    // 通过父节点得到子节点数据
    getTreeDateByParentData (root, treeNodeData, key) {
      new Promise((resolve) => {
        resolve(getMenuByParentMenu(key, this.huiwAppId, {}))
      }).then(res => {
        if (res.code === 'C1') {
          if (root === 0) {
          } else {
            treeNodeData = Object.assign(treeNodeData, { children: [] })
          }
          var menus = res.data
          for (var i = 0; i < menus.length; i++) {
            var tn = {
              title: menus[i].menuName,
              key: menus[i].pid
            }
            if (root !== 0) {
              treeNodeData.children.push(tn)
            } else {
              treeNodeData.push(tn)
            }
            this.allHalfCheckedKeys.push(treeNodeData.key)
            // this.treeData = [...this.treeData]
            this.getTreeDateByParentData(tn.key, tn, tn.key)
          }
        }
      })
    },
    // 初始角色可管理菜单
    getRoleManagerMenu () {
      if (this.huiwAppId === '') {
        return
      }
      this.cardloading = true
      this.treeData = []
      new Promise((resolve) => {
        resolve(this.getTreeDateByParentData(0, this.treeData, this.huiwAppId, {}))
      }).then(res => {
        this.selectedMenuKeys = []
        this.checkedMenuKeys = []
        this.roleAddMenus = []
        this.roleDelMenus = []
        this.cardloading = false
      }).catch(() => {
        // Do something
      }).finally(() => {
      })
    },
    // 树展开按钮
    onExpand () {
      // console.log('Trigger Expand')
    },
    // 树加载节点
    onLoadData (treeNode) {
      console.log(treeNode)
      return new Promise(resolve => {
        if (treeNode.dataRef.children) {
          resolve()
          return
        }
        getMenuByParentMenu(treeNode.dataRef.key, this.huiwAppId, {})
          .then(res => {
            if (res) {
              if (res.code !== 'C0') {
                treeNode.dataRef.children = []
                var menus = res.data
                for (var i = 0; i < menus.length; i++) {
                  var tn = {
                    title: menus[i].menuName,
                    key: menus[i].pid
                  }
                  treeNode.dataRef.children.push(tn)
                }
                this.treeData = [...this.treeData]
              }
            }
          })
        resolve()
      })
    },
    // 添加角色按钮
    handleRoleAdd () {
      this.$refs.RoleModal.showAddModal()
    },
    // 批量删除选中角色
    handleRoleBatchDel () {
      // do
    },
    // 编辑角色信息
    handleRoleEdit (record) {
      this.$refs.RoleModal.showEditModal(record.pid)
    },
    // 关闭提示
    alertOnClose () {
      this.alertVisable = false
    },
    // 应用搜索
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 选中角色 表格行变色
    setRowClassName (record, index) {
      if (record.pid === this.clickedRowKey) {
        return 'clickRowStyle'
      }
    }
  }
}
</script>

<style lang="less">
  .card {
    margin: 10px;
    margin-top: 0px;
    min-height:300px;
    min-width: 300px;
  }
  .role-table-operations {
    margin-bottom: 10px;
    text-align: left;
    height: 30px;
  }
  .role-table-operations > button {
    margin-left: 15px;
    margin-top: 0px;
    margin-bottom: 10px;
    // text-align: right;
  }
  .role-table-operations > input {
    margin-left: 10px;
    // text-align: right;
  }
  .tree-operations {
    margin-bottom: 16px;
    overflow: auto;
    max-height: 500px;
    max-height: calc(100vh - 403px);
    // max-height:-moz-calc(100% - 300px);
    // max-height:-webkit-calc(100% - 300px);
    // float: right;
  }
  .leftCol {
    min-width:300px;
    // margin-right: 10px;
  }
  .cardSelect{
    margin: 10px;
    margin-top: 0px;
    padding: 0px;
    margin-bottom: 10px;
    text-align: left;
    min-width: 300px;
  }
  .cardSelect-select{
    margin-left: 5px;
    widows: 100%;
  }
  .menuInfodiv{
    margin: 10px;
    text-align: center;
  }
  .menuInfodiv > button{
    margin-left: 30px;
  }
  // 表格背景色
  .clickRowStyle{
    background-color:  #e6f7ff;
  }
  .radioStyle {
    // display: block;
    height: 30px;
    padding-top: 300px;
    margin-bottom: 10px;
  }
</style>
